import R from 'ant-design-vue/es/radio/Group'
import dic from '@/utils/dic'
import { axios } from '@/utils/request'

export default {
  model: {
    prop: 'value',
    event: 'change'
  },
  data () {
    return {
      // local + 原始属性，可通过控制 localxxx 来修改 原始属性，以解决 props 属性在子类中修改报错的问题
      localOptions: [],
      localValue: this.value || this.defaultValue || undefined
    }
  },
  // 扩展属性，或覆盖原属性
  props: Object.assign({}, R.props, {
    /**
     * 远程配置 - 使用远程请求数据
     */
    remote: {
      type: Object,
      default: function () {
        return {
          url: '',
          method: 'get',
          params: {},
          formatter: function () {},
          properties: {
            label: '',
            value: ''
          }
        }
      }
    },
    /**
     * 字典类型 - 使用缓存
     */
    dType: {
      type: String
    },
    /**
     * 元素
     * [{label: '显示名称', value: 'number/string', disabled: false}]
     */
    data: {
      type: Array,
      default: function () {
        return []
      }
    }
  }),
  watch: {
    data (val, oldVal) {
      this.optionData = val
    }
  },
  created () {
    if (this.data && this.data.length > 0) {
      // 执行本地数据格式转换
      this.translateData(this.data)
    } else if (this.remote && this.remote.url) {
      const remote = Object.assign({
        header: { 'Content-Type': 'application/json;charset=UTF-8' },
        method: 'get',
        params: {},
        formatter: function () {},
        properties: {
          label: '',
          value: ''
        }
      }, this.remote)
      // 执行远程请求 这里耦合进来 封装方法
      axios(remote, this.remote).then(res => {
        // properties 转换层 做转换处理，formatter 做自定义扩展处理
        this.translateData(res.data || [])
      })
    } else if (this.dType) {
      this.translateData(dic.query(this.dType) || [])
    }
  },
  methods: {
    translateData (data) {
      const options = []
      data.forEach(item => {
        options.push({
          label: `${item.label}`,
          value: item.value,
          key: item.value + '',
          disabled: item.disabled || false
        })
      })
      this.localOptions = options
    },
    handleChange (event) {
      this.localValue = event.target.value
      this.$emit('change', this.localValue, event)
    }
  },
  render () {
    const props = {}
    const localKeys = Object.keys(this.$data)
    Object.keys(R.props).forEach(k => {
      const localKey = `local${k.substring(0, 1).toUpperCase()}${k.substring(1)}`
      if (localKeys.includes(localKey)) {
        props[k] = this[localKey]
        return props[k]
      }
      this[k] && (props[k] = this[k])
      return props[k]
    })

    const radioGroup = (
      <a-radio-group {...{ props, scopedSlots: { ...this.$scopedSlots } }} onChange={this.handleChange}>
        { Object.keys(this.$slots).map(name => (<template slot={name}>{this.$slots[name]}</template>)) }
      </a-radio-group>
    )

    return (
      <div>
        {radioGroup}
      </div>
    )
  }
}
